import sys
import json

from config import getConfigParams
from requestUrl import getDocByUrl,getEntryIdByUrl
from logs import saveLog
from formatContent import formatContent

# 获取配置参数
configParams = getConfigParams(sys.argv)
url = configParams['real_url']
env = configParams['env']

# 获取问题ID 也就是文章ID
articleId = getEntryIdByUrl(configParams['base_url'])

# url = 'https://zhuanlan.zhihu.com/p/259754792'
headers = {
    'referer': 'https://zhuanlan.zhihu.com',
}

# 获取html文本doc，得到pq对象
doc = getDocByUrl(url, headers)

# 图片丢失，被替换成了svg
for figure in doc('figure'):
    noScriptSrc = doc(doc(figure)('img')[0]).attr('src')
    doc(doc(figure)('img')[1]).attr('src', noScriptSrc)

# 【暂时】封面图使用文章中第一张图片
coverUrl = ''
if doc('figure'):
    figure = doc(doc('figure')[0])
    coverUrl = doc(doc(figure)('img')).attr('src')

# 封面图时背景图时
if doc('.TitleImage').attr('style'):
    styleStr = doc('.TitleImage').attr('style')
    styleList = styleStr.split(';')
    for style in styleList:
        if style.find('background') >= 0 and style.find('url(http') >= 0:
            start = style.find('url(http')
            end = style.find(') ')
            coverUrl = style[start + 4:end]
# 标题
title = doc('.Post-Title').text()

# 文章正文
articleContent = doc('.Post-RichText').html()

# 文章作者
authorName = doc('.UserLink-link').text()

# 去【李世泉】那里过滤标签
content = formatContent(articleContent, env=env)

result = {
    'entry_id': articleId,
    'not_format_content': articleContent,
    'content': content,
    'author_name': authorName,
    'cover_url': coverUrl,
    'public_time':
        json.loads(doc('script[id="js-initialData"]').html())['initialState']['entities']['articles'][articleId][
            'created'],
    'description': '',
    'title': title,
}
logData = {
    'params': sys.argv,
    'result': result
}
saveLog(json.dumps(logData, ensure_ascii=False))
print(json.dumps(result, ensure_ascii=False))
